import * as departmentApi from '@/api/department';

const state = {
  departmentList: [],
  company: {},
  managerList: {},
  departmentDetail: {}
}

const mutations = {
  SET_DEPARTMENT_LIST(state, newValue) {
    state.departmentList = newValue
  },
  SET_COMPANY(state, newValue) {
    state.company = newValue
  },
  SET_MANAGER_LIST(state, newValue) {
    state.managerList = newValue
  },
  SET_DEPARMENT_DETAIL(state, newValue) {
    state.departmentDetail = newValue
  },
}

const actions = {
  async updateDepartmentList ({commit}) {
    const res = await departmentApi.department();
    commit('SET_DEPARTMENT_LIST', res)
  },
  async updateCompany ({commit}, id) {
    const res = await departmentApi.company(id);
    commit('SET_COMPANY', res)
  },
  async updateManagerList ({commit}) {
    const res = await departmentApi.getManager();
    commit('SET_MANAGER_LIST', res)
  },
  async updateDepartmentDetail ({commit}, id) {
    const res = await departmentApi.getDepartmentDetail(id);
    commit('SET_DEPARMENT_DETAIL', res)
  },
}


function dataTransfer(data, pid) {
  return data
      .filter(d => d.pid === pid)
      .map(dd => ({
          ...dd,
          children: dataTransfer(data, dd.id)
      }))
}
const getters = {
  departmentTree(state) {
    return dataTransfer(state.departmentList, '')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
